#include"comm.hpp"
int main()
{
    Log("child pid is : ",Debug) << getpid() << endl;
    //1.创建公共的Key
    key_t k = ftok(PATH_NAME,PROJ_ID);
    //ftok如果成功返回key，如果失败返回 -1
    if(k < 0)
    {
        Log("create key failed",Error) << " client key: " << k << endl;
        exit(1);
    }
    Log("create key done",Debug) << " client key: " << k << endl;

    //2.获取共享内存地址
    int shmid = shmget(k,SHM_SIZE,0);
    if(shmid < 0)
    {
        Log("create shm failed",Error) << " shmid: " << shmid << endl;
        exit(2); 
    }
    Log("create shm success",Debug) << " shmid: " << shmid << endl;
    // sleep(10);

    //3.挂接共享内存
    char *shmaddr = (char*)shmat(shmid,nullptr,0);
    if(shmaddr == nullptr)
    {
        Log("attach shm failed", Error) << " client key: " << shmid << endl;
        exit(3);
    }
    Log("attach shm success",Debug) << " client key: " << shmid << endl;
    // sleep(10);
    int fd = OpenFIFO(FIFO_NAME,WRITE);
    //使用,
    //client将共享内存看作一个char类型的buffer
    while(true)
    {
        ssize_t s = read(0,shmaddr,SHM_SIZE-1);
        if(s > 0)
        {
            shmaddr[s - 1] = 0;
            Signal(fd); //唤醒服务器端wait的地方来读取
            if(strcmp(shmaddr,"quit") == 0) break;
        }
    }
    CloseFifo(fd);

    // char a = 'a';
    // for(; a <= 'z'; ++a)
    // {
    //     shmaddr[a-'a'] = a;
    //     //每一次都想shmaddr[共享内存的起始地址]写入
    //     // snprintf(shmaddr,SHM_SIZE - 1,\
    //     //     "hello server,我是其他进程，我的pid: %d, inc: %c\n",getpid(),a);
    //      sleep(5);
    // }

    // strcpy(shmaddr,"quit");

    //将指定的共享内存，从自己的地址空间中去关联
    int n = shmdt(shmaddr);
    //shmdt,成功0，失败1
    assert(n != -1);
    Log("detach shmid done",Debug) << " shmid: " << shmid << endl;
    // sleep(10);
    
    //客户端不需要关闭，使用就行
    return 0;
}